package com.echo.register.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.echo.register.hosp.repository.DepartmentRepository;
import com.echo.register.hosp.service.DepartmentService;
import com.echo.register.model.hosp.Department;
import com.echo.register.vo.hosp.DepartmentQueryVo;
import com.echo.register.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: DepartmentServiceImpl
 * @Package: com.echo.register.hosp.service.impl
 * @Description: 科室上传API接口
 * @Author 谢同学
 * @Create 2023/12/20 10:34
 * @Version 1.0
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 上传科室信息
     *
     * @param paramMap 医院编号
     */
    @Override
    public void saveDepartment(Map<String, Object> paramMap) {
        // 数据转对象：先转json数据再转对象
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Department.class);

        // 判断科室信息是否已经存在
        Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        if (!StringUtils.isEmpty(targetDepartment)) {
            // 不为空修改
            department.setUpdateTime(new Date());

        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
        }
        department.setIsDeleted(0);
        departmentRepository.save(department);
    }

    /**
     * 分页查询
     *
     * @param page              当前页码
     * @param limit             每页记录数
     * @param departmentQueryVo 查询条件
     * @return
     */
    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        //构建排序条件
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 构建分页条件
        PageRequest pageRequest = PageRequest.of(page - 1, limit, sort);

        // 转换数据格式
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);

        // 封装查询
        Example<Department> example = Example.of(department, matcher);

        Page<Department> departmentPage = departmentRepository.findAll(example, pageRequest);
        return departmentPage;
    }

    /**
     * 删除科室
     *
     * @param hoscode
     * @param depcode
     */
    @Override
    public void deleteDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            department.setIsDeleted(1);
            departmentRepository.save(department);
        }
    }

    /**
     * 根据医院编号，查询医院所有科室列表
     *
     * @param hoscode 医院编号
     * @return 科室列表树型数据
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 用于返回最终数据
        List<DepartmentVo> result = new ArrayList<>();
        // 查询全部数据
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        departmentQuery.setIsDeleted(0); // 查询删除状态为0的数据
        Example<Department> example = Example.of(departmentQuery);

        List<Department> departmentList = departmentRepository.findAll(example);
        // 为了方便操作 将list转为map，Key 大科室编号 value 该大科室对应的小科室列表

        Map<String, List<Department>> map = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        // 遍历map
        for (Map.Entry<String, List<Department>> entry : map.entrySet()) {
            // 获取大科室编号
            String depcode = entry.getKey();
            // 获取该大科室下面的小科室列表
            List<Department> smallList = entry.getValue();
            // 组装大科室
            DepartmentVo bigVo = new DepartmentVo(); //存放大科室
            bigVo.setDepcode(depcode); // 大科室编号
            bigVo.setDepname(smallList.get(0).getDepname());// 大科室名称

            // 组装小科室
            List<DepartmentVo> smallVoList = new ArrayList<>();//用于存放小科室
            for (Department department : smallList) {
                DepartmentVo samllVo = new DepartmentVo();
                samllVo.setDepname(department.getDepname()); //小科室名称
                samllVo.setDepcode(department.getDepcode()); //小科室编号
                smallVoList.add(samllVo);
            }

            bigVo.setChildren(smallVoList); // 大科室对应的小科室

            result.add(bigVo);
        }
        return result;
    }

    /**
     * 获取科室名字
     *
     * @param hoscode 医院编号
     * @param depcode 科室编号
     * @return
     */
    @Override
    public String getDepName(String hoscode, String depcode) {
        String depname = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode).getDepname();
        if (depname != null) {
            return depname;
        }
        return null;
    }

    /**
     * 获取科室信息
     *
     * @param hoscode 医院编号
     * @param depcode 科室编号
     * @return
     */
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode);
    }


}

